package com.weijing.pretty_app.dialog

import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.util.DisplayMetrics
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.MutableLiveData
import com.weijing.pretty_app.databinding.DialogUpgradeBinding
import com.weijing.pretty_app.util.CoreUtil
import com.weijing.pretty_app.util.ProgressResponseBody
import okhttp3.Call
import java.io.File

private const val TAG = "UpgradeDialog"

/**
 * app升级弹窗
 */
class UpgradeDialog(
    private val apkUrl: String, private val newVersionNumber: String, private val callback: Callback
) : DialogFragment() {

    private lateinit var binding: DialogUpgradeBinding
    private val progressLiveData = MutableLiveData<Int>()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?,
    ): View {
        binding = DialogUpgradeBinding.inflate(inflater, container, false)

        binding.dialogUpGradeTvVersionNumber.text = newVersionNumber

        binding.dialogUpGradeTvUpGrade.setOnClickListener {
            if (apkUrl.isNullOrEmpty()) return@setOnClickListener

            val savePath =
                requireContext().getExternalFilesDir(null)!!.absolutePath + File.separatorChar + "download"
            Log.i(TAG, "apk下载路径-- $apkUrl -apk保存的路径: $savePath")
            downloadApk(apkUrl, savePath, newVersionNumber)
        }

        binding.dialogUpGradeIvClose.setOnClickListener {
            dismiss()
        }

        progressLiveData.observe(requireActivity()) { num ->
            binding.dialogUpGradeTvUpGrade.visibility = View.GONE
            binding.dialogUpGradeClProgressBar.visibility = View.VISIBLE
            binding.dialogUpGradeTvProgress.text = num.toString() + "%"
        }
        dialog?.window?.setBackgroundDrawable(ColorDrawable(resources.getColor(android.R.color.transparent)))
        return binding.root
    }

    override fun onStart() {
        super.onStart()
        isCancelable = false    //点击外部不可取消
        val dm = DisplayMetrics()
        this.activity?.windowManager?.defaultDisplay?.getMetrics(dm)
        this.dialog?.window?.setLayout(dm.widthPixels, dm.heightPixels)
    }

    private fun downloadApk(apkUrl: String, savePath: String, newVersionNumber: String) {
        CoreUtil.downLoadFileWithProgress(
            apkUrl, savePath, "com.light.v${newVersionNumber}-app.apk",
            object : ProgressResponseBody.ProgressListener {
                override fun update(bytesRead: Long, contentLength: Long, done: Boolean) {
                    val percent = (bytesRead * 100 / contentLength).toInt()
                    if (percent > 0) {
                        progressLiveData.postValue(percent)
                    }
                    binding.dialogUpGradeProgressBar.post {
                        binding.dialogUpGradeProgressBar.progress = percent
                    }
                }

                override fun newCall(call: Call) {

                }

                override fun failed() {
                    dismiss()
                }

                override fun success(filePath: String) {
                    callback.downLoadSuccess(filePath)
                }
            })
    }

    interface Callback {

        //下载完成
        fun downLoadSuccess(filePath: String)
    }
}